import c3d from "../../cc";
import { ProxyOb } from "./Core/ProxyOb";
import VmBase, { COMP_MAP_ARR } from "./Core/VmBase";

/*
 * @features: 主要功能
 * @description: 内容说明
 * @Date: 2021-09-11 16:15:03
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2021-10-03 23:03:20
 * @LastEditors: judu233
 */
const { ccclass, property, menu } = c3d._decorator;


@ccclass(`VmSpriteParme`)
class VmSpriteParme {
    @property({ type: [c3d.SpriteFrame], tooltip: 'sprite将会用到帧图片' })
    spriteFrames: Array<c3d.SpriteFrame> = [null];

    @property
    private _spriteIndex: number = 0;
    @property({ tooltip: '当前显示的spriteFrame', type: c3d.CCInteger, min: 0, })
    get index() { return this._spriteIndex; }
    set index(value: number) {
        this._spriteIndex = c3d.misc.clampf(parseInt(String(value)), 0, this.spriteFrames.length - 1);
        this.changeSprite();
    }

    sp: c3d.Sprite;

    /**设置 Sprite 组件的spriteFrame属性，变换图片     */
    changeSprite() {
        this.sp.spriteFrame = this.spriteFrames[this.index];
    }
}

@ccclass(`VmSprite`)
@menu('VM/VM-Sprite')
export default class VmSprite extends VmBase {
    /**代理的实体组件 比如Label,直接操控可以更改数据模型， 直接使用 proxy.string = xxx*/
    proxy: ProxyOb<c3d.Sprite>['proxy'];

    /**监听的组件对象 */
    _watchComponent: c3d.Sprite = null;

    @property(VmSpriteParme)
    parmeSet = new VmSpriteParme();

    onEditor() {
        this.parmeSet.sp = this.node.getComponent(c3d.Sprite);
        super.onEditor();
    }

    onDataInit() {
        this.parmeSet.sp = this.node.getComponent(c3d.Sprite);
        super.onDataInit();
    }

    onDataChange(n, o) {
        this.parmeSet.index = n;
    }

    _checkComponent() {
        let arr = COMP_MAP_ARR.get(this.watch.componentName);
        this.watch._watchComponent = this.getComponent(arr[0]);
        if (!this.watch._watchComponent || !this.watch.componentProperty) {
            c3d.warn(`节点${this.node.name}未设置需要监听的组件/属性`);
            return false;
        }
        if (!this.watch._watchComponent.enabled)
            return false;
        return true;
    }

    /**通过设置帧名字来设置对象 */
    setName(name: string) {
        let index = this.parmeSet.spriteFrames.findIndex(v => { return v.name == name });
        if (index < 0) { c3d.error('frameIndex 设置了不存在的name:', name) }
        this.parmeSet.index = index || 0;
    }

    /**随机范围设置帧图片 */
    random(min = 0, max = 0) {
        if (!this.parmeSet.spriteFrames) return;
        min = c3d.misc.clampf(min, 0, this.parmeSet.spriteFrames.length);
        max = c3d.misc.clampf(max, 0, this.parmeSet.spriteFrames.length);
        this.parmeSet.index = Math.floor(Math.random() * (max - min) + min);
    }

    fast_next() { this.parmeSet.index++; }
    fast_previous() { this.parmeSet.index--; }
}
